package com.dd.cloud.open.service.impl;

import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.open.api.AICMSServiceClient;
import com.dd.cloud.open.enums.ResponseEnum;
import com.dd.cloud.open.exception.ApiException;
import com.dd.cloud.open.req.api.*;
import com.dd.cloud.open.res.api.*;
import com.dd.cloud.open.service.IApiService;
import com.dd.cloud.open.service.IOpenUserApplyService;
import com.dd.cloud.user.entity.aicms.AicmsDepartment;
import com.dd.cloud.user.entity.aicms.AicmsDisease;
import com.dd.cloud.user.entity.aicms.AicmsDoctor;
import com.dd.cloud.user.entity.aicms.AicmsSymptom;
import com.dd.cloud.user.req.aicms.AskDoctorParamsReq;
import com.dd.cloud.user.vo.DiagnosticRecordVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Lx
 * @version 1.0
 * @date 2023/9/28
 */
@Service
public class ApiServiceImpl implements IApiService {
    private AICMSServiceClient aicmsServiceClient;
    private IOpenUserApplyService openUserApplyService;
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    public void setAicmsServiceClient(AICMSServiceClient aicmsServiceClient) {
        this.aicmsServiceClient = aicmsServiceClient;
    }

    @Resource
    public void setOpenUserApplyService(IOpenUserApplyService openUserApplyService) {
        this.openUserApplyService = openUserApplyService;
    }

    @Resource
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public DiagnoseRes ask(HttpServletRequest request, HttpServletResponse response, DiagnoseReq req) {
        Integer userId = verify(req.getAppId(), req.getSign(), req.getTimestamp());
        AskDoctorParamsReq paramsReq = new AskDoctorParamsReq();
        paramsReq.setUserID(userId);
        paramsReq.setUserType(LoginInfo.UserType.OPEN);
        paramsReq.setDiseasename(req.getDiseaseName());
        paramsReq.setZzName(req.getSymptomNames());
        paramsReq.setIds(req.getSymptomIds());
        paramsReq.setXuhao(req.getDiseaseNo());
        paramsReq.setXB(req.getSex());
        paramsReq.setNL(req.getAge());
        paramsReq.setZB(req.getNation());
        paramsReq.setHYZK(req.getMarriage());
        paramsReq.setFlag(req.getFlag());
        paramsReq.setXM(req.getName());
        paramsReq.setLXDH(req.getPhone());
        ResponseEntity<DiagnosticRecordVo> voRes = aicmsServiceClient.ask(paramsReq);
        DiagnoseRes res = new DiagnoseRes();
        DiagnosticRecordVo vo = verifyResponseBody(voRes.getBody());
        res.setFlag(vo.getFlag());
        res.setErrorMsg(vo.getSErrorMsg());
        res.setErrorCode(vo.getNErrorCode());
        if (vo.getNErrorCode() != 0) {
            return res;
        }
        res.setResult(vo.getRecord().getResult());
        res.setCaseFileDoc(vo.getRecord().getCaseFileDoc());
        res.setPrescription(vo.getRecord().getPrescription());
        res.setAdvisoryPrescription(vo.getRecord().getAdvisoryPrescription());
        return res;
    }

    @Override
    public List<DepartmentRes> department(HttpServletRequest request, HttpServletResponse response, AuthReq req) {
        verify(req.getAppId(), req.getSign(), req.getTimestamp());
        List<AicmsDepartment> list = aicmsServiceClient.queryDepartMents().getBody();
        if (list == null) {
            return Collections.emptyList();
        }
        List<DepartmentRes> res = new ArrayList<>(list.size());
        DepartmentRes departmentRes;
        for (AicmsDepartment item : list) {
            departmentRes = new DepartmentRes();
            departmentRes.setDepartmentId(item.getNID());
            departmentRes.setDepartmentName(item.getSName());
            res.add(departmentRes);
        }
        return res;
    }

    @Override
    public List<DiseaseRes> disease(HttpServletRequest request, HttpServletResponse response, DiseaseReq req) {
        verify(req.getAppId(), req.getSign(), req.getTimestamp());
        List<AicmsDisease> list;
        if (req.getDepartmentId() != null) {
            list = aicmsServiceClient.queryDiseases(req.getDepartmentId() + "").getBody();
        } else {
            if (req.getDiseaseId() == null) {
                throw new ApiException(ResponseEnum.DISEASE_AND_DEPARTMENT_NOT_NULL);
            }
            list = aicmsServiceClient.querySubDiseases(req.getDiseaseId() + "").getBody();
        }
        if (list == null) {
            return Collections.emptyList();
        }
        List<DiseaseRes> res = new ArrayList<>(list.size());
        DiseaseRes diseaseRes;
        for (AicmsDisease item : list) {
            diseaseRes = new DiseaseRes();
            diseaseRes.setDepartmentId(item.getDepartmentId());
            diseaseRes.setDiseaseId(item.getNID());
            diseaseRes.setDiseaseName(item.getSName());
            if (req.getDiseaseId() != null) {
                diseaseRes.setDiseasePid(req.getDiseaseId());
            } else {
                diseaseRes.setDiseasePid(item.getPId());
            }
            diseaseRes.setDiseaseNo(item.getSXuHao());
            diseaseRes.setHaveChild(item.getNHaveChild());
            res.add(diseaseRes);
        }
        return res;
    }

    @Override
    public List<SymptomRes> symptom(HttpServletRequest request, HttpServletResponse response, SymptomReq req) {
        verify(req.getAppId(), req.getSign(), req.getTimestamp());
        List<AicmsSymptom> list = aicmsServiceClient.querySymptoms(req.getDiseaseNo()).getBody();
        if (list == null) {
            return Collections.emptyList();
        }
        List<SymptomRes> res = new ArrayList<>(list.size());
        SymptomRes symptomRes;
        for (AicmsSymptom item : list) {
            symptomRes = new SymptomRes();
            symptomRes.setDiseaseNo(item.getPXuhao());
            symptomRes.setSymptomId(item.getSID());
            symptomRes.setSymptomName(item.getSName());
            res.add(symptomRes);
        }
        return res;
    }

    @Override
    public DoctorRes doctor(HttpServletRequest request, HttpServletResponse response, DoctorReq req) {
        verify(req.getAppId(), req.getSign(), req.getTimestamp());
        AicmsDoctor doctor = aicmsServiceClient.queryDoctor(req.getDiseaseId() + "").getBody();
        DoctorRes res = new DoctorRes();
        if (doctor == null) {
            return res;
        }
        res.setExpertInfo(doctor.getSInfo());
        res.setExpertJobTitle(doctor.getSZhicheng());
        res.setExpertName(doctor.getSPerson());
        res.setExpertPhoto(doctor.getSPhoto());
        res.setAuthor(doctor.getSAutoer());
        res.setSoftRegistryNum(doctor.getSWork());
        res.setDiseaseId(Integer.valueOf(doctor.getNID()));
        res.setDiseaseNo(doctor.getSXuHao());
        res.setDiseaseName(doctor.getSName());
        res.setDepartmentId(doctor.getSKeshi().isEmpty() ? -1 : Integer.parseInt(doctor.getSKeshi()));
        return res;
    }

    public Integer verify(String applyId, String sign, Long timestamp) {
        Integer userId = openUserApplyService.verifyUserApp(applyId, sign, timestamp);
        if (userId == -1) {
            throw new ApiException(ResponseEnum.APPLY_INFO_ERROR);
        }
        return userId;
    }

    public <T> T verifyResponseBody(T body) {
        if (body == null) {
            throw new ApiException(ResponseEnum.SYSTEM_ERROR);
        }
        return body;
    }
}
